home *** CD-ROM | disk | FTP | other *** search
/ CD Actual 80 / CD Actual 80 Julio-Agosto 2003.iso / Linux / LinuxGazette / lg / issue39 / rogers_example05e.c < prev    next >
Encoding:
C/C++ Source or Header  |  2002-08-14  |  1.3 KB  |  62 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. /*
  5.     This program is written to demonstrate the <stdlib.h> library.
  6.     This program will demonstrate memory allocation using calloc and realloc.
  7.     Written by James M. Rogers
  8.     21 March 1999
  9.     Released to the Public Domain on this date.
  10. */
  11.  
  12. /*
  13.     Read in lines from a file, reallocating memory as needed, then freeing when done.
  14. */
  15.  
  16. #define SIZE 1024
  17.  
  18. main(int argv, char *argc[]){
  19.  
  20.     char *file;
  21.     char line[SIZE];
  22.     FILE *stream;
  23.     unsigned int mem_size, file_size, line_size;
  24.  
  25.     mem_size=SIZE;
  26.     file_size=0;
  27.  
  28.     if((file=calloc(1,SIZE))==(char *)NULL){
  29.     printf("Cannot allocate memory.\n");
  30.     exit (1);
  31.     }
  32.  
  33.     if((stream=fopen(argc[1], "r")) == (FILE *)NULL){
  34.     printf("Cannot open file.");
  35.     exit (1);
  36.     }
  37.  
  38.     while(fgets(line, SIZE+1, stream) != (char *)NULL) { 
  39.         printf("%s",line);
  40.     line_size=strlen(line);
  41.         file_size += line_size;
  42.         while(file_size>mem_size) {
  43.         mem_size += SIZE;
  44.         if ((file=realloc(file, mem_size)) == (char *)NULL){
  45.         printf("Cannot allocate memory.\n");
  46.                 free(file);
  47.         fclose(stream);
  48.         exit (1);
  49.         }
  50.         }
  51.         strcat(file,line);
  52.     printf("allocated memory:%d \t file size:%d \t size of line:%d\n", mem_size, file_size, line_size);
  53.      
  54.     }
  55.  
  56.     printf("%s",file);
  57.  
  58.     fclose(stream);
  59.     free(file);
  60.     exit (0);
  61. }
  62.